<template>
  <div>
    <BasicModal width="80%" v-bind="$attrs" @register="registerModal" :title="getTitle" @ok="sub">
      <BasicForm @register="registerForm">
        <!-- <template #imgUrlSlot="{ model, field }">
          <BasicUpload v-model:file-list="model[field]"
                       :api="UploadApi"
                       :maxNumber="1"
                       :accept="['jpg', 'png', 'JPG', 'PNG']"
                       :multiple="false"
                       :maxSize="5" />
        </template> -->
      </BasicForm>
      <div class="hint"> 建议图片尺寸：宽750*高268rpx </div>
    </BasicModal>
  </div>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref, h } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  // import { listApi } from '/@/api/set/menu';
  import { ListApi, AddApi, UpdateApi, UploadApi } from '/@/api/article/index';
  import { classification } from '/@/assets/dic';
  import { useComponentRegister } from '/@/components/Form';
  import { listToTree } from '/@/utils/helper/treeHelper';
  import { FormSchema } from '/@/components/Table';
  import { Tinymce } from '/@/components/Tinymce/index';
  import { getAppEnvConfig } from '/@/utils/env';
  import { throttle } from '/@/utils/throttle';
  import { BasicUpload } from '/@/components/Upload';
  import { GetcitylistApi } from '/@/api/activityAdmin/index';
  import { Select } from 'ant-design-vue';
  useComponentRegister('Tinymce', Tinymce);
  interface Ioptions {
    key: Number | String;
    label: String;
    value: Number | String;
  }
  export const formSchema: FormSchema[] = [
    {
      label: 'id',
      field: 'id',
      component: 'Input',
      show: false,
    },
    {
      field: 'title',
      label: '文章标题:',
      component: 'Input',
      required: true,
    },
    {
      field: 'type',
      label: '文章分类:',
      component: 'Select',
      componentProps: {
        options: classification,
        // [
        //   { label: '留学生课堂', value: 0 },
        //   { label: '关于留学生网', value: 1 },
        //   { label: '大楼介绍', value: 2 },
        // ],
      },
    },
    // {
    //   field: 'imgUrl',
    //   label: '文章封面:',
    //   component: 'Upload',
    // },
    {
      field: 'imgUrl',
      label: '文章封面',
      component: 'Upload',
      // slot: 'imgUrlSlot',
      componentProps: {
        api: UploadApi,
        maxNumber: 1,
        accept: ['jpg', 'png', 'JPG', 'PNG'],
        multiple: false,
        maxSize: 5,
      },
      rules: [
        {
          required: true,
          message: '请上传banner图片文件',
        },
      ],
      colProps: {
        span: 16,
      },
    },
    {
      label: '区域：',
      field: 'city',
      component: 'ApiSelect',
      componentProps: {
        api: GetcitylistApi,
        numberToString: true,
        resultField: 'data',
        labelField: 'city',
        valueField: 'id',
      },
      rules: [
        {
          required: true,
          message: '请选择区域',
          trigger: 'change',
        },
      ],
      colProps: {
        span: 16,
      },
    },
    {
      field: 'publisher',
      label: '作者:',
      component: 'Input',
      required: true,
    },

    {
      label: '文章内容:',
      field: 'content',
      component: 'Tinymce',
      componentProps: {
        uploadUrl: getAppEnvConfig().VITE_GLOB_API_URL + '/baseinfo/articleManager/getFileUrl',
      },
      colProps: { lg: 24, md: 24 },
    },
  ];

  export default defineComponent({
    name: 'MenuModal',
    components: { BasicModal, BasicForm, BasicUpload, Select },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const isUpdate = ref(true);
      // 市区选择框
      const cityOptions = ref<Ioptions[]>([]);
      const [registerForm, { resetFields, setFieldsValue, updateSchema, validate }] = useForm({
        labelWidth: 160,
        schemas: formSchema,
        showActionButtonGroup: false,
        baseColProps: { lg: 12, md: 24 },
      });

      const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
        resetFields();
        isUpdate.value = !!data?.isUpdate;
        if (data.record) {
          if (data.record.city) {
            data.record.city = String(data.record.city);
          }
          const imgList = [data.record.imgUrl];
          setFieldsValue({
            ...data.record,
            imgUrl: imgList,
          });
        } else {
          setFieldsValue({
            content: ' ',
          });
        }
        const treeData = await queryList();
        updateSchema({
          field: 'parentId',
          componentProps: {
            treeData,
          },
        });
      });

      async function queryList() {
        const params = {
          pageNum: 1,
          pageSize: 10,
        };
        const data = await ListApi(params);
        if (data.data) {
          return listToTree(data.data, {
            id: 'id',
            pid: 'parentId',
            children: 'parentId',
          });
        }
        return [];
      }

      const getTitle = computed(() => (!unref(isUpdate) ? '新增文章' : '编辑文章'));

      async function handleSubmit() {
        try {
          setModalProps({ confirmLoading: true });
          console.log(await validate(), '验证');
          const values = await validate();
          values.imgUrl = values.imgUrl[0];
          values.parentId = 0 | values.parentId;
          if (values.id > 0) {
            await UpdateApi(values);
          } else {
            await AddApi(values);
          }
          closeModal();
          emit('success');
        } catch (err) {
          console.log(err);
        } finally {
          setModalProps({ confirmLoading: false });
        }
      }
      const sub = throttle(handleSubmit);
      return { registerModal, registerForm, getTitle, sub, cityOptions };
    },
  });
</script>
<style lang="less" scoped>
  .hint {
    position: absolute;
    top: 13%;
    left: 23%;
    color: red;
  }
  @media screen and (min-width: 1600px) {
    .hint {
      top: 13%;
      left: 23%;
    }
  }
  @media screen and (min-width: 1300px) {
    .hint {
      top: 13%;
      left: 29%;
    }
  }
  @media screen and (max-width: 1299px) {
    .hint {
      top: 13%;
      left: 34%;
    }
  }
  @media screen and (max-width: 986px) {
    .hint {
      top: 22%;
      left: 39%;
    }
  }
</style>
